package com.yuexiao.config;

import com.yuexiao.service.DetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName:SecurityConfig
 * @Auther: YUEXIAO
 * @Description: 权限配置
 * @Date: 2022/8/13 09:23
 * @Version: v1.0
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DetailsService detailsService;
    @Autowired
    private MyAuthenticationSuccessHandler successHandler;
    @Autowired
    private MyAuthenticationFailureHandler failureHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭csrf，开启跨域请求
        http.csrf().disable().cors();

        //设置自定义登录页
        http.formLogin()
                .loginPage("/backend/page/login/login.html")
                .loginProcessingUrl("/employee/login")
                .successHandler(successHandler)
                .failureHandler(failureHandler)
                .permitAll();

        //设置释放资源
        http.authorizeRequests()
                .antMatchers("/backend/images/**","/backend/api/**","/backend/js/**","/backend/plugins/**","/backend/styles/**","/employee/login","/employee/logout")
                .permitAll();

        //设置权限资源
        http.authorizeRequests()
                .antMatchers("/backend/index.html","/backend/page/**")
                .access("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')").anyRequest().authenticated();

        //设置登出
        http.logout()
                .logoutUrl("/employee/logout")
                .permitAll();

        //支持frame
        http.headers().frameOptions().disable();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(detailsService).passwordEncoder(password());
    }

    @Bean
    PasswordEncoder password(){
        return new BCryptPasswordEncoder();
    }
}
